<template>
  <div class="gi_page">
    <a-spin :loading="loading">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        auto-label-width
        label-align="left"
        :layout="width >= 500 ? 'horizontal' : 'vertical'"
        :disabled="!isUpdate"
        scroll-to-first-error
        class="form"
      >
        <a-form-item
          field="protocol"
          label="邮件协议"
          help="邮件发送协议类型"
          hide-asterisk
        >
          <a-select v-model.trim="form.protocol">
            <a-option label="SMTP" value="smtp" />
          </a-select>
        </a-form-item>
        <a-form-item
          field="host"
          label="服务器地址"
          help="邮件服务器地址"
          hide-asterisk
        >
          <a-input v-model.trim="form.host" />
        </a-form-item>
        <a-form-item
          field="port"
          label="服务器端口"
          help="邮件服务器连接端口"
          hide-asterisk
        >
          <a-input-number v-model="form.port" :min="0" />
        </a-form-item>
        <a-form-item
          field="userName"
          label="邮箱账号"
          help="发件人登录帐户"
          hide-asterisk
        >
          <a-input v-model.trim="form.userName" />
        </a-form-item>
        <a-form-item
          field="from"
          label="邮箱地址"
          help="发件人邮箱地址，发件人邮箱地址"
          hide-asterisk
        >
          <a-input v-model.trim="form.from" />
        </a-form-item>
        <a-form-item
          field="password"
          label="邮箱密码"
          help="服务授权密码/客户端专用密码"
          hide-asterisk
        >
          <a-input-password v-model.trim="form.password" autocomplete="off" />
        </a-form-item>
        <a-form-item
          field="sslEnabled"
          label="启用SSL加密"
          help="是否启用SSL/TLS加密连接"
          hide-asterisk
        >
          <a-switch
            v-model="form.ssl"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
          >
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </a-switch>
        </a-form-item>
        <a-form-item
          v-if="form.ssl"
          field="sslPort"
          label="mSSL端口号"
          help="SSL加密连接的备用端口（通常与主端口一致）"
          hide-asterisk
        >
          <a-input-number v-model="form.sslPort" :min="0" />
        </a-form-item>
        <a-space style="margin-bottom: 16px">
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" type="primary" @click="onUpdate">
            <template #icon><icon-edit /></template>修改
          </a-button>
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" @click="onResetValue">
            <template #icon><icon-undo /></template>恢复默认
          </a-button>
          <a-button v-if="isUpdate" type="primary" @click="handleSave">
            <template #icon><icon-save /></template>保存
          </a-button>
          <a-button v-if="isUpdate" @click="reset">
            <template #icon><icon-refresh /></template>重置
          </a-button>
          <a-button v-if="isUpdate" @click="handleCancel">
            <template #icon><icon-undo /></template>取消
          </a-button>
        </a-space>
      </a-form>
    </a-spin>
    <a-alert v-if="isAlert" :type="alerttype">{{ alertText }}</a-alert>
  </div>
</template>

<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'
import { type FormInstance, Message, Modal } from '@arco-design/web-vue'
import type {
  Email,
  EmailResp,
} from '@/apis/plugin/type'
import {
  CheckHealth,
  GetDataSource,
  UpdateDataSource,
} from '@/apis/plugin/datasource'
import { useResetReactive } from '@/hooks'
import { encryptByRsa } from '@/utils/encrypt'

defineOptions({ name: 'SystemMailConfig' })
const { width } = useWindowSize()
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const [form] = useResetReactive({
  id: '',
  version: '',
  name: '',
  protocol: '',
  from: '',
  host: '',
  port: 0,
  userName: '',
  password: '',
  ssl: false,
  sslPort: 0,
})
const rules: FormInstance['rules'] = {
  host: [{ required: true, message: '请输入值' }],
  port: [{ required: true, message: '请输入值' }],
  userName: [{ required: true, message: '请输入值' }],
  from: [{ required: true, message: '请输入值' }],
  password: [{ required: true, message: '请输入值' }],
  sslPort: [{ required: true, message: '请输入值' }],
}
const isAlert = ref(false)
const alerttype = ref('success')
const alertText = ref('')
// 重置
const reset = () => {
  formRef.value?.resetFields()
}

const isUpdate = ref(false)
// 修改
const onUpdate = () => {
  isUpdate.value = true
}

// 取消
const handleCancel = () => {
  reset()
  isUpdate.value = false
}

// 查询列表数据
const getDataList = async () => {
  loading.value = true
  const { data } = await GetDataSource('email')
  Object.assign(form, data.jsonData)
  form.id = data.id
  form.version = data.version
  form.name = data.name
  loading.value = false
}

// 保存
const handleSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) return false
  const formData = ref({
    id: form.id,
    name: form.name,
    version: form.version,
    // remark: '邮件配置',
    securejsonData: '',
    jsondata: {
      protocol: form.protocol,
      from: form.from,
      host: form.host,
      port: form.port,
      userName: form.userName,
      ssl: form.ssl,
      sslPort: form.sslPort,
    },
  })
  formData.value.securejsonData = JSON.stringify({ password: encryptByRsa(form.password) })
  await UpdateDataSource(formData.value)
  await getDataList()
  Message.success('保存成功')
  // 检查健康状态
  const result = await CheckHealth('email')
  isAlert.value = true
  if (result.success) {
    isAlert.value = true
    alerttype.value = 'success'
    alertText.value = '配置成功'
  } else {
    alerttype.value = 'error'
    alertText.value = `配置失败，原因:${result.msg}`
  }
}

// 恢复默认
const handleResetValue = async () => {
  Message.success('恢复成功')
  await getDataList()
}
const onResetValue = () => {
  Modal.warning({
    title: '警告',
    content: '确认恢复邮件配置为默认值吗？',
    hideCancel: false,
    maskClosable: false,
    onOk: handleResetValue,
  })
}

onMounted(() => {
  getDataList()
})
</script>

<style scoped lang="scss">
:deep(.arco-form-item.arco-form-item-has-help) {
  margin-bottom: 5px;
}

:deep(.form .arco-input-wrapper),
:deep(.arco-select-view-single) {
  width: 220px;
}
</style>
